/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.unipar.cursoweb.controle;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;

/**
 *
 * @author Thiago Marques
 */
@Controller
@Scope("view")
@Named("loginBean")
public class LoginBean {

    public void login() {
        try {
            ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
            RequestDispatcher dispatcher = ((HttpServletRequest) context.getRequest()).getRequestDispatcher("/j_spring_security_check");
            dispatcher.forward((HttpServletRequest) context.getRequest(), (HttpServletResponse) context.getResponse());
            FacesContext.getCurrentInstance().responseComplete();
            SecurityContext contextSpring = SecurityContextHolder.getContext();
            User user = null;
            if (contextSpring instanceof SecurityContext) {
                Authentication authentication = contextSpring.getAuthentication();
                if (authentication instanceof Authentication) {
                    user = (User) authentication.getPrincipal();
                }
            }
            HttpSession session = (HttpSession) context.getSession(false);
//            session.setAttribute("usuarioLogado", user.getUsername());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void logout() {
        try {
            FacesContext ctx = FacesContext.getCurrentInstance();
            HttpSession session = (HttpSession) ctx.getExternalContext().getSession(false);
            session.setAttribute("usuarioLogado", null);
            ctx.getExternalContext().redirect(ctx.getExternalContext().getRequestContextPath() + "/login.jsf");
            session.invalidate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public String getUsuarioLogado() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        HttpSession session = (HttpSession) context.getSession(false);
        String usuario = (String) session.getAttribute("usuarioLogado");
        return usuario;
    }
}
